package com.shujia.mr.tuijian;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

/*
    tom hello hadoop cat
    <tom-hello,1>
    ...
    <tom-cat,1>
    <hello-hadoop,-1>
    <hello-cat,-1>
    <hadoop-cat,-1>

 */

public class PersonMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        String line = value.toString();
        String[] persons = line.split(" ");
        for (int i = 1; i < persons.length; i++) {
            //直接好友
            context.write(new Text(orderPerson(persons[0], persons[i])), new LongWritable(1L));
            for (int j = i + 1; j < persons.length; j++) {
                context.write(new Text(orderPerson(persons[i], persons[j])), new LongWritable(-1L));
            }
        }
    }

    public String orderPerson(String s1, String s2) {
        String s = null;
        if (s1.compareTo(s2) < 0) {
            s = s1 + "-" + s2;
        } else if (s1.compareTo(s2) > 0) {
            s = s2 + "-" + s1;
        }
        return s;
    }
}
